<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>lower_bound</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C++ Algorithms</a> &gt; <a href=
    "lower_bound.html">lower_bound</a>
  </div>

  <div class="name-format">
    lower_bound
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #include &lt;algorithm&gt;
  iterator lower_bound( iterator first, iterator last,  const <a href=
"../containers.html">TYPE</a>&amp; val );
  iterator lower_bound( iterator first, iterator last, const <a href=
"../containers.html">TYPE</a>&amp; val, CompFn f );
</pre>

  <p>The lower_bound() function is a type of <a href=
  "binary_search.html">binary_search</a>(). This function searches for
  the first place that <em>val</em> can be inserted into the ordered
  range defined by <em>first</em> and <em>last</em> that will not mess
  up the existing ordering.</p>

  <p>The return value of lower_bound() is an iterator that points to
  the location where <em>val</em> can be safely inserted. Unless the
  comparison function <em>f</em> is specified, the &lt; operator is
  used for ordering.</p>

  <p>For example, the following code uses lower_bound() to insert the
  number 7 into an ordered vector of integers:</p>
  <pre class="example-code">
 vector&lt;int&gt; nums;
 nums.push_back( -242 );
 nums.push_back( -1 );
 nums.push_back( 0 );
 nums.push_back( 5 );
 nums.push_back( 8 );
 nums.push_back( 8 );
 nums.push_back( 11 );          

 cout &lt;&lt; &quot;Before nums is: &quot;;
 for( unsigned int i = 0; i &lt; nums.size(); i++ ) {
   cout &lt;&lt; nums[i] &lt;&lt; &quot; &quot;;
 }
 cout &lt;&lt; endl;            

 vector&lt;int&gt;::iterator result;
 int new_val = 7;               

 result = lower_bound( nums.begin(), nums.end(), new_val );             

 nums.insert( result, new_val );                

 cout &lt;&lt; &quot;After, nums is: &quot;;
 for( unsigned int i = 0; i &lt; nums.size(); i++ ) {
   cout &lt;&lt; nums[i] &lt;&lt; &quot; &quot;;
 }
 cout &lt;&lt; endl;            
</pre>

  <p>The above code produces the following output:</p>
  <pre class="example-code">
 Before nums is: -242 -1 0 5 8 8 11
 After, nums is: -242 -1 0 5 7 8 8 11           
</pre>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="binary_search.html">binary_search</a><br>
    <a href="equal_range.html">equal_range</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
